package com.ruyuan.starter.jedis.autoconfigure;

import com.ruyuan.starter.jedis.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.Objects;

/**
 * @author zhonghuashishan
 */
/*
配置例子
ruyuan:
  jedis:
    maxTotal: 10
    maxIdel: 10
    minIdel: 1
    redisAddrs:
      - 192.168.199.18:7001
      - 192.168.199.18:7002
      - 192.168.199.18:7003
      - 192.168.199.18:7004
      - 192.168.199.18:7005
      - 192.168.199.18:7006
 */
@Configuration
@EnableConfigurationProperties(JedisConfig.class)
public class JedisAutoConfiguratioin {

    private final JedisConfig jedisConfig;

    public JedisAutoConfiguratioin(JedisConfig jedisConfig) {
        if (Objects.isNull(jedisConfig.getMaxTotal())) {
            jedisConfig.setMaxTotal(8);
        }
        if (Objects.isNull(jedisConfig.getMaxIdle())) {
            jedisConfig.setMaxIdle(8);
        }
        if (Objects.isNull(jedisConfig.getMinIdle())) {
            jedisConfig.setMinIdle(0);
        }
        if (Objects.isNull(jedisConfig.getRedisAddrs()) || jedisConfig.getRedisAddrs().isEmpty()) {
            jedisConfig.setRedisAddrs(Collections.singletonList("127.0.0.1:6379"));
        }
        this.jedisConfig = jedisConfig;
    }

    @Bean(destroyMethod = "destroy")
    @ConditionalOnMissingBean
    public JedisManager jedisManager() {
        return new JedisManager(jedisConfig);
    }

    @Bean(name = "redisCacheService")
    @ConditionalOnMissingBean
    public CacheSupport redisCacheService(JedisManager jedisManager) {
        return new RedisCacheSupport(jedisManager);
    }

    @Bean(name = "redisLockService")
    @ConditionalOnMissingBean
    public LockService redisLockService(JedisManager jedisManager) {
        return new RedisLockService(jedisManager);
    }
}